#include "randnum.h"
#include <windows.h>
#include <fstream>
#include <sortthread.h>
#include <iostream>
using namespace std;

/*快排调用算法*/
/*传入参数**SortObject结构体***/
void SortThread::quickSort(SortObject *pvector)
{
    //QString res;
    int l = 0, r;
    r = this->size;
    //cout<<r<<endl<<endl;
    sortTle = 0;
    sortMov = 0;
    sortCmp = 0;
    quick(pvector, l, r-1);
    ofstream outfile("e://sortplus.txt");
    outfile << "快排" << endl << "排序趟数：" << sortTle << "     移动次数：" << sortMov << "     比较次数：" << sortCmp;// << endl;
    for(int i = 0; i < size; i++)
    {
        senda(i,-10);
    }
}

/*快排递归实现*/
/*传入参数**SortObject结构体**扫描开始位置**扫描结束位置***/
void SortThread::quick(SortObject *pvector, int l, int r)
{
    int i, j;
    RecordNode temp, *data = pvector->record;
    if (l >= r)
    {
        return;
    }
    i = l;
    j = r;
    temp = data[i];

    while (i != j)
    {
        sortCmp++;
        this->sendt(sortTle,sortMov,sortCmp);
        while (i < j&&data[j].key >= temp.key)
        {
            sortCmp++;
            catched1 = i;
            catched2 = j;
            this->sendt(sortTle,sortMov,sortCmp);
            j--;
            //Sleep(frd);
            for(int ii =0; ii < this->size; ii++)
            {
                catched1 = i;
                catched2 = j;
                this->sendArray[ii] = pvector->record[ii].key;
            }
            this->senda(catched1,catched2);
        }
        if (i < j)
        {
            data[i++] = data[j];
            sortMov++;
            sortCmp++;
            this->sendt(sortTle,sortMov,sortCmp);
            //Sleep(frd);
            for(int ii =0; ii < this->size; ii++)
            {
                this->sendArray[ii] = pvector->record[ii].key;
            }
            catched1 = i;
            catched2 = j;
            this->senda(catched1,catched2);
        }
        while (i < j && data[i].key <= temp.key)
        {
            sortCmp++;
            catched1 = i;
            catched2 = j;
            this->sendt(sortTle,sortMov,sortCmp);
            i++;
            this->senda(catched1,catched2);
        }
        if (i < j)
        {
            catched1 = i;
            catched2 = j;
            data[j--] = data[i];
            sortCmp++;
            sortMov++;
            this->sendt(sortTle,sortMov,sortCmp);
            for(int ii =0; ii < this->size; ii++)
            {
                this->sendArray[ii] = pvector->record[ii].key;
            }
            this->senda(catched1,catched2);
        }
    }
    data[i] = temp;

    for(int ii =0; ii < this->size; ii++)
    {
        catched1 = i;
        catched2 = j;
        this->sendArray[ii] = pvector->record[ii].key;
    }

    sortTle++;
    this->sendt(sortTle,sortMov,sortCmp);
    this->senda(catched1,catched2);
    catched1 = i;
    catched2 = j;

    quick(pvector, l, i - 1);
    quick(pvector, i + 1, r);
}

